#!/usr/bin/env python
"""
启动脚本：初始化数据库并启动Django服务器
"""
import os
import sys
import subprocess
import time

def run_command(command):
    """运行命令并打印输出"""
    print(f"执行命令: {command}")
    process = subprocess.Popen(
        command, 
        shell=True, 
        stdout=subprocess.PIPE, 
        stderr=subprocess.STDOUT,
        universal_newlines=True
    )
    
    if process.stdout:
        for line in process.stdout:
            print(line.strip())
    
    process.wait()
    return process.returncode

def main():
    # 获取脚本所在目录
    script_dir = os.path.dirname(os.path.abspath(__file__))
    os.chdir(script_dir)
    
    # 检查MySQL服务是否运行
    print("检查MySQL服务...")
    try:
        import MySQLdb
        conn = MySQLdb.connect(
            host="127.0.0.1",
            user="root",
            passwd="123456",
            port=3306
        )
        conn.close()
        print("MySQL服务正在运行")
    except Exception as e:
        print(f"无法连接到MySQL服务: {e}")
        print("请确保MySQL服务已启动，且用户名和密码正确")
        return
    
    # 初始化数据库
    print("\n初始化数据库...")
    setup_result = run_command("python script/setup_db.py")
    if setup_result != 0:
        print("数据库初始化失败")
        return
    
    # 应用Django迁移
    print("\n应用Django迁移...")
    migrate_result = run_command("python manage.py migrate")
    if migrate_result != 0:
        print("应用迁移失败")
        return
    
    # 启动Django服务器
    print("\n启动Django服务器...")
    print("服务器将在 http://localhost:8000 上运行")
    print("按Ctrl+C停止服务器")
    
    # 设置CORS允许所有来源
    os.environ['CORS_ALLOW_ALL_ORIGINS'] = 'True'
    
    # 启动服务器
    run_command("python manage.py runserver 0.0.0.0:8000")

if __name__ == "__main__":
    main() 